package server

import (
	"sort"
	"strings"

	"gitee.com/douxuefeng/go-utils/strutil"
	"gitee.com/douxuefeng/go-utils/wechat/corp/config"
	"gitee.com/douxuefeng/go-utils/wechat/corp/params"
)

type callBack struct {
	cf *config.CorpConfig
}

func NewCallBack(cf *config.CorpConfig) *callBack {
	return &callBack{
		cf: cf,
	}
}

/**
 * @name: 回调验证url
 * @description:
 * @param {params.CallBackParams} para
 * @return {*}
 */
func (a *callBack) VerifyUrl(para params.CallBackParams) string {
	var str = []string{a.cf.Token, para.Timestamp, para.Nonce, para.EchoStr}
	sort.Strings(str)
	encryptStr := strutil.Sha1(strings.Join(str, ""))
	if encryptStr == para.MsgSignature {
		// 解密消息
		aesKey := strutil.Base64Decoding(a.cf.EncodingAesKey + "=")
		aesMsg := strutil.Base64Decoding(para.EchoStr)
		randMsg, err := strutil.AesDecrypt(aesMsg, aesKey)
		if err != nil {
			return ""
		}
		return randMsg
	}
	return ""
}
